
package com.ruhua.java.service;

import com.ruhua.java.dao.Category;
import com.ruhua.java.dto.CategoryDTO;
import com.ruhua.java.exception.NotFoundException;
import com.ruhua.java.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


@Service
public class CategoryService {
    @Autowired
    CategoryRepository categoryRepository;

    public Category getById(Long num) {
        return categoryRepository.findOneByCategoryId(num);
    }

    public Optional<Category> getByName(String name) {
        return categoryRepository.findByShortName(name);
    }


    public void createItem(CategoryDTO dto) {
        Category item = Category.builder()
                .categoryName(dto.getCategoryName())
                .pid(dto.getPid())
                .categoryPic(dto.getCategoryPic())
                .shortName(dto.getShortName())
                .build();
        categoryRepository.save(item);
    }

    public List<Category> findAll(){
        return categoryRepository.findAll();
    }

    public void updateItem(CategoryDTO dto) {
        Category item = this.getById(dto.getCategoryId());
        item.setCategoryName(dto.getCategoryName());
        item.setCategoryPic(dto.getCategoryPic());
        item.setPid(dto.getPid());
        item.setShortName(dto.getShortName());
        categoryRepository.save(item);
    }

    public void delItem(Long id) {
        try {
            categoryRepository.deleteById(id);
        } catch (Exception e) {
            throw new NotFoundException(10001);
        }
    }

}
